package main

import (
	"context"
	"embed"
	"fmt"
	"log"
	"net/http"

	"oil-drilling-monitor/backend"

	"github.com/wailsapp/wails/v2"
	"github.com/wailsapp/wails/v2/pkg/options"
	"github.com/wailsapp/wails/v2/pkg/options/assetserver"
)

//go:embed all:frontend/dist
var assets embed.FS

// App struct
type App struct {
	ctx          context.Context
	server       *backend.Server
	witsReceiver *backend.WITSReceiver
	logger       *backend.Logger
}

// CORS middleware to allow all origins
func corsMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// Allow all origins
		w.Header().Set("Access-Control-Allow-Origin", "*")
		// Allow common HTTP methods
		w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		// Allow common headers
		w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")

		// Handle preflight requests
		if r.Method == "OPTIONS" {
			w.WriteHeader(http.StatusOK)
			return
		}

		next(w, r)
	}
}

// NewApp creates a new App application struct
func NewApp() *App {
	// 初始化日志系统
	logger, err := backend.NewLogger("./logs")
	if err != nil {
		log.Printf("Failed to initialize logger: %v", err)
		// 使用标准日志作为后备
		logger = nil
	}

	srv := backend.NewServer()
	witsReceiver := backend.NewWITSReceiver("0.0.0.0", 5001, "./data/wits_raw")

	// 如果日志器创建成功，设置给WITS接收器
	if logger != nil {
		witsReceiver.SetLogger(logger)
	}

	// 如果日志器创建成功，记录启动信息
	if logger != nil {
		logger.Info("Application starting up...")
		logger.Info("Logger initialized successfully")
	}

	return &App{
		server:       srv,
		witsReceiver: witsReceiver,
		logger:       logger,
	}
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx

	// 记录应用启动
	if a.logger != nil {
		a.logger.Info("Application startup initiated")
	}

	if a.logger != nil {
		a.logger.Info("Database initialized successfully")
	}

	// 注册WebSocket处理函数 (带CORS支持)
	http.HandleFunc("/api/ws", corsMiddleware(a.server.HandleWebSocket))

	// 注册钻机配置API处理函数 (带CORS支持)
	http.HandleFunc("/api/drill-config", corsMiddleware(a.server.GetDrillConfigHandler))         // GET method
	http.HandleFunc("/api/drill-config/write", corsMiddleware(a.server.WriteDrillConfigHandler)) // POST method

	if a.logger != nil {
		a.logger.Info("WebSocket handler registered")
		a.logger.Info("Drill config API handlers registered")
	}

	// 设置WITS接收器的数据处理回调
	a.witsReceiver.SetDataHandler(func(data []byte, clientAddr string) {
		// 使用自定义日志器记录WITS数据
		if a.logger != nil {
			a.logger.Info("Processing WITS data from %s: %s", clientAddr, string(data))
		} else {
			// 后备方案：使用标准日志
			log.Printf("Processing WITS data from %s: %s", clientAddr, string(data))
		}

		// 创建消息并广播给WebSocket客户端
		// message := backend.Message{
		// 	T: time.Now().Unix(),
		// 	D: 100.0, // 示例数据，实际应该从WITS数据解析
		// 	F: 150.0,
		// }

		// // 广播给WebSocket客户端
		// a.server.BroadcastMessage(message)
	})

	// 启动WITS-A接收服务
	go func() {
		if a.logger != nil {
			a.logger.Info("Starting WITS-A receiver service on port 5001")
		}

		if err := a.witsReceiver.Start(); err != nil {
			if a.logger != nil {
				a.logger.Error("Failed to start WITS receiver: %v", err)
			} else {
				log.Printf("Failed to start WITS receiver: %v", err)
			}
		} else {
			if a.logger != nil {
				a.logger.Info("WITS-A receiver service started successfully")
			}
		}
	}()

	if a.logger != nil {
		a.logger.Info("Application startup completed")
	}
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}

// CleanOldLogs 清理旧的日志文件
func (a *App) CleanOldLogs(daysToKeep int) error {
	if a.logger != nil {
		if err := a.logger.CleanOldLogs(daysToKeep); err != nil {
			a.logger.Error("Failed to clean old logs: %v", err)
			return err
		}
		a.logger.Info("Cleaned logs older than %d days", daysToKeep)
		return nil
	}
	return fmt.Errorf("Logger not initialized")
}

// GetLogFiles 获取日志文件列表
func (a *App) GetLogFiles() ([]string, error) {
	if a.logger != nil {
		return a.logger.GetLogFiles()
	}
	return nil, fmt.Errorf("Logger not initialized")
}

// LogInfo 记录信息日志
func (a *App) LogInfo(message string) {
	if a.logger != nil {
		a.logger.Info("Frontend: %s", message)
	}
}

// LogWarning 记录警告日志
func (a *App) LogWarning(message string) {
	if a.logger != nil {
		a.logger.Warning("Frontend: %s", message)
	}
}

// LogError 记录错误日志
func (a *App) LogError(message string) {
	if a.logger != nil {
		a.logger.Error("Frontend: %s", message)
	}
}

func main() {
	// Create an instance of the app structure
	app := NewApp()

	// 启动HTTP服务用于WebSocket (端口8888)
	go func() {
		app.Greet("Starting WebSocket server")
		fmt.Println("Starting HTTP server on :8888")
		if err := http.ListenAndServe(":8888", nil); err != nil {
			fmt.Printf("HTTP server error: %v\n", err)
		}
	}()

	// Create application with options
	err := wails.Run(&options.App{
		Title:  "oil-drilling-monitor",
		Width:  1024,
		Height: 768,
		AssetServer: &assetserver.Options{
			Assets: assets,
		},
		BackgroundColour: &options.RGBA{R: 27, G: 38, B: 54, A: 1},
		OnStartup:        app.startup,
		Bind: []interface{}{
			app,
		},
	})

	if err != nil {
		println("Error:", err.Error())
	}
}
